<template>
  <el-dialog v-model="cxsjDialog" title="" @closed="handleclose">
    <div v-if="pcVisible">
      <el-table :data="events" stripe height="300px" row-height="100">
        <el-table-column
          property="number"
          label="事件编号"
          width="100"
          height="20px"
        />
        <el-table-column
          property="type"
          label="事件类型"
          width="100"
          height="20px"
        />
        <el-table-column
          property="level"
          label="事件等级"
          width="100"
          height="20px"
        />
        <el-table-column
          property="time"
          label="发生时间"
          width="100"
          height="20px"
        />
        <el-table-column
          property="addr"
          label="发生地点"
          width="100"
          height="20px"
        />
        <el-table-column
          property="insignia"
          label="车牌号"
          width="100"
          height="20px"
        />
        <el-table-column
          property="driver"
          label="驾驶员"
          width="100"
          height="20px"
        />
        <el-table-column
          property="statusnew"
          label="处理状态"
          width="100"
          height="20px"
        />
      </el-table>
      <el-pagination
        v-model:current-page="currentPage2"
        v-model:page-size="pageSize2"
        :page-sizes="[1, 5, 10, 20]"
        :small="small"
        :background="true"
        pager-count="5"
        layout="sizes, prev, pager, next"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <template v-else="pcVisible">
      <el-button @click="istype = true">按类型统计</el-button>
      <el-button @click="istype = false">按月份统计</el-button>
      <h2>交通事件({{ events.length }}起)</h2>
      <PieChart v-if="istype" :data="arr" v-bind="config" />
      <PieChart v-else="istype" :data="arr2" v-bind="config" />
    </template>
    <template #header>
      <span class="dialog-header">
        <el-button @click="handlehot">生成事件热力图</el-button>
        <el-button type="primary" @click="handlesta">生成事件统计图</el-button>
      </span>
    </template>
  </el-dialog>
  <el-button v-if="subggbtn" class="subgg" @click="closehot"
    >关闭热力图</el-button
  >
</template>

<script setup>
import { useUsersStore } from '@/stores/user'
import { storeToRefs } from 'pinia'
import { onMounted, ref, watch } from 'vue'
import { Query } from '@/zondy_api/Query.js'
import { PieChart } from '@opd/g2plot-vue'
// import { Query } from '../../../zondy_api/Query.js'
import { useGlobalMap } from '@/utils/globalMap.js'
// import { onMounted } from 'vue'
let map
let heatmapSource
onMounted(() => {
  map = useGlobalMap()
})
const store = useUsersStore()
const { activeIndex, cxsjDialog, positionBox } = storeToRefs(store)
let events = ref([])
//控制视图切换
const pcVisible = ref(true)
const subggbtn = ref(false)
let arr = ref([])
let arr2 = ref([])
let istype = ref(true)
const currentPage2 = ref(1)
const pageSize2 = ref(5)
const total = ref(0)
watch(
  () => store.cxsjDialog,
  () => {
    if (store.cxsjDialog) {
      var service = {
        name: 'guanggu',
        layerId: 2,
      }
      Query.queryByGeom({
        geometry: store.positionBox,
        service,
        pageIndex: 0,
        recordNumber: 1000,
        success: (res) => {
          total.value = res.SFEleArray.length
        },
      })
      Query.queryByGeom({
        geometry: store.positionBox,
        service,
        pageIndex: 0,
        recordNumber: 5,
        success: (res) => {
          seltbysizepage(res)
        },
      })
    }
  }
)
//
function handleSizeChange() {
  var service = {
    name: 'guanggu',
    layerId: 2,
  }
  Query.queryByGeom({
    geometry: store.positionBox,
    service,
    pageIndex: currentPage2.value - 1,
    recordNumber: pageSize2.value,
    success: (res) => {
      seltbysizepage(res)
    },
  })
}
function handleCurrentChange() {
  var service = {
    name: 'guanggu',
    layerId: 2,
  }
  Query.queryByGeom({
    geometry: store.positionBox,
    service,
    pageIndex: currentPage2.value - 1,
    recordNumber: pageSize2.value,
    success: (res) => {
      seltbysizepage(res)
    },
  })
}
//处理查询后的结果
function seltbysizepage(res) {
  const SFEleArray = res.SFEleArray
  const AttValue = SFEleArray.map((item) => item.AttValue)
  events.value = []
  AttValue.map((item) => {
    let event = {
      number: item[0],
      type: item[1],
      level: item[2],
      time: item[3],
      addr: item[4],
      insignia: item[5],
      driver: item[6],
      statusnew: item[7],
    }
    events.value.push(event)
  })
}
//生成热力图
function handlehot() {
  subggbtn.value=true
  let service = {
    name: 'guanggu',
    layerId: 2,
  }
  // 根据图层查询
  Query.queryByGeom({
    geometry: store.positionBox,
    service,
    pageIndex: 0,
    recordNumber: 1000,
    success: (res) => {
      console.log(res.SFEleArray[0].AttValue)
      var format = new Zondy.Format.PolygonJSON()
      var features = format.read(res)
      // console.log(features);

      // 设置要素权值
      // parseFloat() 函数可解析一个字符串,并返回一个浮点数
      for (var i = 0; i < features.length; i++) {
        features[i].set(
          'weight',
          parseFloat(res.SFEleArray[i].AttValue[2]) * 0.3
        )
      }
      if (!heatmapSource) {
        heatmapSource = new ol.source.Vector({
          wrapX: false,
        })
        var heatmapLayer = new ol.layer.Heatmap({
          source: heatmapSource,
          radius: 10,
          blur: 10,
        })
        map.addLayer(heatmapLayer)
      }
      heatmapSource.addFeatures(features)
    },
  })
  store.cxsjDialog = false
  store.activeIndex = '0'
}
//关闭热力图
function closehot(){
  heatmapSource.clear()
  subggbtn.value=false
}
function handleclose() {
  store.cxsjDialog = false
  store.activeIndex = '0'
}
//饼图设置
function handlesta() {
  arr.value = []
  arr2.value = []
  pcVisible.value = !pcVisible.value
  const data = []
  const datastyle = []
  const datatime = []
  events.value.forEach((item) => {
    datastyle.push(item.type)
    datatime.push(item.time.split('.')[1])
  })
  // console.log(datatime);
  // console.log(datastyle)
  // 统计数组中相同元素的个数
  let obj = {}
  for (let i = 0; i < datastyle.length; i++) {
    if (obj[datastyle[i]]) {
      obj[datastyle[i]]++
    } else {
      obj[datastyle[i]] = 1
    }
  }
  // console.log(obj);
  // 将相同元素的个数转换为数组
  for (let key in obj) {
    arr.value.push({
      id: key,
      name: obj[key],
    })
  }
  // console.log(arr.value)

  //获取月份
  let obj2 = {}
  for (let i = 0; i < datatime.length; i++) {
    if (obj2[datatime[i]]) {
      obj2[datatime[i]]++
    } else {
      obj2[datatime[i]] = 1
    }
  }
  // console.log(obj);
  // 将相同元素的个数转换为数组
  for (let key in obj2) {
    arr2.value.push({
      id: key,
      name: obj2[key],
    })
  }
  // console.log(arr.value)
}

const config = {
  appendPadding: 10,
  arr: istype.value ? arr : arr2,
  angleField: 'name',
  colorField: 'id',
  radius: 0.6,
  label: {
    type: 'inner',
    offset: '-30%',
    content: ({ percent }) => `${(percent * 100).toFixed(0)}%`,
    style: {
      fontSize: 14,
      textAlign: 'center',
    },
  },
  interactions: [{ type: 'element-active' }],
}
</script>

<style scoped>
.subgg {
  position: fixed;
  top: 50px;
  right: 20px;
}
</style>
